package com.daxt.controller.infomanager;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.BehaveLogType;
import com.daxt.model.dic.DicDocFileType;
import com.daxt.model.dic.DicDocState;
import com.daxt.model.search.ArchivesSearch;
import com.daxt.model.service.archives.vo.ArchivesBehaveLog;
import com.daxt.service.ArchivesBehaveLogService;
import com.daxt.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesDestroyRecordMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.model.service.archives.param.SetStateParam;
import com.daxt.model.service.archives.result.ArchivesList;
import com.daxt.model.service.archives.vo.ArchivesDestroyRecord;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.service.DocService;
import com.daxt.utils.LocalDateTimeUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "档案整理")
@RestController
@RequestMapping("/infoManage")
public class FileManageController {

    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private UserInfoUtil userInfoUtil;
    /*
     * @Autowired private ArchivesTypeDocMapper archivesTypeDocMapper;
     *
     * @Autowired private ArchivesTypeMapper archivesTypeMapper;
     *
     * @Autowired private DocFileRespository docFileRespository;
     */
    @Autowired
    private DocService docService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ArchivesDestroyRecordMapper archivesDestroyRecordMapper;
    @Autowired
    private ArchivesBehaveLogService archivesBehaveLogService;

    @ApiOperation(value = "件列表", notes = "")
    @GetMapping("/doc")
    public Result<ArchivesList> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
                                     @ApiParam("") @RequestParam(value = "typeId", required = false) String typeId,
                                     @ApiParam("") @RequestParam(value = "classId", required = false) String classId,
                                     @ApiParam("") @RequestParam(value = "dossierId", required = false) String dossierId,
                                     @ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
                                     @ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
                                     @ApiParam("部门") @RequestParam(value = "deptId", required = false) String deptId) {


        ArchivesSearch as = ArchivesSearch.builder().fondsId(fondsId).typeId(typeId).classId(classId)
                .condition(condition)
                .keywords(keywords)
                .fileType(DicDocFileType.DOC.getKey())
                .deptId(deptId)
                .state(DicDocState.archive.getKey())
                .isDelete(BaseConstants.DELETE_NORMAL)
                .dossierId(dossierId)
                .build();


        return docService.list(pageNum, pageSize,as);
    }

    @ApiOperation(value = "卷列表", notes = "")
    @GetMapping("/dossier")
    public Result<ArchivesList> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
                                     @ApiParam("") @RequestParam(value = "typeId", required = false) String typeId,
                                     @ApiParam("") @RequestParam(value = "classId", required = false) String classId,
                                     @ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
                                     @ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
                                     @ApiParam("部门") @RequestParam(value = "deptId", required = false) String deptId) {


        ArchivesSearch as = ArchivesSearch.builder().fondsId(fondsId).typeId(typeId).classId(classId)
                .condition(condition)
                .keywords(keywords)
                .fileType(DicDocFileType.DOSSIER.getKey())
                .deptId(deptId)
                .state(DicDocState.archive.getKey())
                .isDelete(BaseConstants.DELETE_NORMAL)
                .dossierId("0")
                .build();

        return docService.list(pageNum, pageSize, as);
    }

//	@ApiOperation(value = "设置鉴定状态", notes = "")
//	@PutMapping("/appraisal/{type}")
//	@Transactional(rollbackFor = Exception.class)
//	public Result<String> setappraisal(@PathVariable("type") String type, @RequestBody List<String> ids,
//			HttpServletRequest request) {
//		UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
//		if (ids != null && ids.size() > 0) {
//			try {
//			for (String string : ids) {
//				ArchivesDoc entity = new ArchivesDoc();
//				entity.setId(Long.valueOf(string));
//				entity.setState("3");
//				archivesDocMapper.updateById(entity);
//
//				ArchivesDestroyRecord archivesDestroyRecord = new ArchivesDestroyRecord();
//				ArchivesDoc selectById = archivesDocMapper.selectById(string);
//				archivesDestroyRecord.setArchivalNum(selectById.getArchivalNum());
//				archivesDestroyRecord.setArchivalYear(selectById.getArchivalYear());
//				archivesDestroyRecord.setFileId(selectById.getId());
//				archivesDestroyRecord.setfondsNum(selectById.getfondsNum());
//				archivesDestroyRecord.setTitle(selectById.getTitle());
//				archivesDestroyRecord.setModel("doc".equals(selectById.getFileType())?"件":"卷");
//				archivesDestroyRecord.setCreateBy(loginInfo.getRealName());
//				archivesDestroyRecord.setCreateTime(LocalDateTimeUtil.getNowTimeYMD());
//				archivesDestroyRecord.setState("0");
//				if("3".equals(type)) {
//					archivesDestroyRecord.setIdentType("销毁");
//				}else {
//					archivesDestroyRecord.setProlongTime("2".equals(type) ? "控制" : "开放");
//					archivesDestroyRecord.setIdentType("划控");
//				}
//				archivesDestroyRecordMapper.insert(archivesDestroyRecord);
//
//				ArchivesDoc selectById1 = archivesDocMapper.selectById(string);
//				if (selectById1.getDossierId().intValue() > 0) {
//					ArchivesDoc selectById2 = archivesDocMapper.selectById(selectById1.getDossierId());
//					if (selectById2 != null) {
//						QueryWrapper<ArchivesDestroyRecord> wrapperDel = new QueryWrapper<ArchivesDestroyRecord>();
//						wrapperDel.eq("state", "0");
//						wrapperDel.eq("fileId", selectById2.getId());
//						archivesDestroyRecordMapper.delete(wrapperDel);
//						ArchivesDestroyRecord archivesDestroyRecord1 = new ArchivesDestroyRecord();
//						archivesDestroyRecord1.setArchivalNum(selectById2.getArchivalNum());
//						archivesDestroyRecord1.setArchivalYear(selectById2.getArchivalYear());
//						archivesDestroyRecord1.setFileId(selectById2.getId());
//						archivesDestroyRecord1.setfondsNum(selectById2.getfondsNum());
//						archivesDestroyRecord1.setTitle(selectById2.getTitle());
//						archivesDestroyRecord1.setModel("doc".equals(selectById2.getFileType())?"件":"卷");
//						archivesDestroyRecord1.setCreateBy(loginInfo.getRealName());
//						archivesDestroyRecord1.setCreateTime(LocalDateTimeUtil.getNowTimeYMD());
//						archivesDestroyRecord1.setState("0");
//						if("3".equals(type)) {
//							archivesDestroyRecord1.setIdentType("销毁");
//							archivesDestroyRecord1.setProlongTime("0");
//						}else {
//							archivesDestroyRecord1.setProlongTime("2".equals(selectById2.getOpenState()) ? "控制" : "开放");
//							archivesDestroyRecord1.setIdentType("划控");
//						}
//
//						archivesDestroyRecordMapper.insert(archivesDestroyRecord1);
//						ArchivesDoc entity1 = new ArchivesDoc();
//						entity1.setId(selectById2.getId());
//						entity1.setState("3");
//						archivesDocMapper.updateById(entity1);
//					}
//				} else if ("dossier".equals(selectById1.getFileType())) {
//					QueryWrapper<ArchivesDoc> queryWrapperDossier = new QueryWrapper<>();
//					queryWrapperDossier.eq("dossierId", selectById1.getId());
//					List<ArchivesDoc> selectList = archivesDocMapper.selectList(queryWrapperDossier);
//					if (selectList != null && selectList.size() > 0) {
//						for (ArchivesDoc archivesDoc : selectList) {
//							QueryWrapper<ArchivesDestroyRecord> wrapperDel = new QueryWrapper<ArchivesDestroyRecord>();
//							wrapperDel.eq("state", "0");
//							wrapperDel.eq("fileId", archivesDoc.getId());
//							archivesDestroyRecordMapper.delete(wrapperDel);
//
//							ArchivesDestroyRecord archivesDestroyRecord1 = new ArchivesDestroyRecord();
//							archivesDestroyRecord1.setArchivalNum(archivesDoc.getArchivalNum());
//							archivesDestroyRecord1.setArchivalYear(archivesDoc.getArchivalYear());
//							archivesDestroyRecord1.setFileId(archivesDoc.getId());
//							archivesDestroyRecord1.setfondsNum(archivesDoc.getfondsNum());
//							archivesDestroyRecord1.setTitle(archivesDoc.getTitle());
//							archivesDestroyRecord1.setCreateBy(loginInfo.getRealName());
//							archivesDestroyRecord1.setCreateTime(LocalDateTimeUtil.getNowTimeYMD());
//							archivesDestroyRecord1.setState("0");
//							archivesDestroyRecord1.setModel("doc".equals(archivesDoc.getFileType())?"件":"卷");
//							if("3".equals(type)) {
//								archivesDestroyRecord1.setIdentType("销毁");
//								archivesDestroyRecord1.setProlongTime("1");
//							}else {
//								archivesDestroyRecord1.setProlongTime("2".equals(type) ? "控制" : "开放");
//								archivesDestroyRecord1.setIdentType("划控");
//							}
//
//							archivesDestroyRecordMapper.insert(archivesDestroyRecord1);
//							ArchivesDoc entity1 = new ArchivesDoc();
//							entity1.setId(archivesDoc.getId());
//							entity1.setState("3");
//							archivesDocMapper.updateById(entity1);
//						}
//					}
//				}
//
//			}
//		}catch (Exception e) {
//			e.printStackTrace();
//			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
//		}
//			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
//		}
//		return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
//	}

    @ApiOperation(value = "加入鉴定", notes = "")
    @PostMapping("/appraisal")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()
    public Result<String> list(@ApiIgnore @LoginUser UserInfo loginUser,
                               @RequestBody SetStateParam setStateParam,
                               HttpServletRequest request) {
        try {
            List<String> ids = setStateParam.getIds();
            try {
                for (String string : ids) {
                    if ("doc".equals(setStateParam.getType())) {
                        ArchivesDoc entity = new ArchivesDoc();
                        entity.setId(Long.parseLong(string));
                        entity.setState("3");
                        archivesDocMapper.updateById(entity);
                    } else if ("dossier".equals(setStateParam.getType())) {
                        ArchivesDoc entity = new ArchivesDoc();
                        entity.setId(Long.parseLong(string));
                        entity.setState("3");
                        int update = archivesDocMapper.updateById(entity);
                        if (update <= 0) {
                            throw new Exception();
                        }
                        UpdateWrapper<ArchivesDoc> updateWrapper = new UpdateWrapper<ArchivesDoc>();
                        updateWrapper.in("dossierId", ids);
                        ArchivesDoc docEntity = new ArchivesDoc();
                        docEntity.setState("3");
                        archivesDocMapper.update(docEntity, updateWrapper);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
            }
            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(ids), BehaveLogType.APPRAISAL.getKey(),BehaveLogType.APPRAISAL.getValue(),null),loginUser ,request);
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
        } catch (Exception e) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", "");
        }
    }

//	@ApiOperation(value = "设置保管期限", notes = "")
//	@PostMapping("/setArchivalYear/{fileType}/{value}")
//	@Transactional(rollbackFor = Exception.class)
//	public Result<String> setArchivalYear(@PathVariable("fileType") String fileType,
//			@PathVariable("value") String value, @RequestBody List<Long> ids, HttpServletRequest request) {
//		UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
//		if (loginInfo == null) {
//			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请重新登录！！！", null);
//		}
//		try {
//			for (Long string : ids) {
//				if ("doc".equals(fileType)) {
//					ArchivesDoc entity = new ArchivesDoc();
//					entity.setId(string);
//					entity.setState("3");
//					int updateById = archivesDocMapper.updateById(entity);
//					if (updateById > 0) {
//						ArchivesDestroyRecord archivesDestroyRecord = new ArchivesDestroyRecord();
//						ArchivesDoc selectById = archivesDocMapper.selectById(string);
//						archivesDestroyRecord.setArchivalNum(selectById.getArchivalNum());
//						archivesDestroyRecord.setArchivalYear(selectById.getArchivalYear());
//						archivesDestroyRecord.setFileId(selectById.getId());
//						archivesDestroyRecord.setfondsNum(selectById.getfondsNum());
//						archivesDestroyRecord.setCreateBy(loginInfo.getRealName());
//						archivesDestroyRecord.setTitle(selectById.getTitle());
//						archivesDestroyRecord.setCreateTime(LocalDateTimeUtil.getNowTimeYMD());
//						archivesDestroyRecord.setState("0");
//						archivesDestroyRecord.setProlongTime(value);
//						archivesDestroyRecord.setIdentType("延期");
//						archivesDestroyRecordMapper.insert(archivesDestroyRecord);
//					}
//				} else if ("dossier".equals(fileType)) {
//					ArchivesDoc entity = new ArchivesDoc();
//					entity.setId(string);
//					entity.setState("3");
//					int update = archivesDocMapper.updateById(entity);
//					if (update <= 0) {
//						throw new Exception();
//					}
//					ArchivesDestroyRecord archivesDestroyRecord = new ArchivesDestroyRecord();
//					ArchivesDoc selectById = archivesDocMapper.selectById(string);
//					archivesDestroyRecord.setArchivalNum(selectById.getArchivalNum());
//					archivesDestroyRecord.setArchivalYear(selectById.getArchivalYear());
//					archivesDestroyRecord.setFileId(selectById.getId());
//					archivesDestroyRecord.setfondsNum(selectById.getfondsNum());
//					archivesDestroyRecord.setTitle(selectById.getTitle());
//					archivesDestroyRecord.setCreateBy(loginInfo.getRealName());
//					archivesDestroyRecord.setCreateTime(LocalDateTimeUtil.getNowTimeYMD());
//					archivesDestroyRecord.setState("0");
//					archivesDestroyRecord.setProlongTime(value);
//					archivesDestroyRecord.setIdentType("延期");
//					archivesDestroyRecordMapper.insert(archivesDestroyRecord);
//					UpdateWrapper<ArchivesDoc> updateWrapper = new UpdateWrapper<ArchivesDoc>();
//					updateWrapper.in("dossierId", ids);
//					ArchivesDoc docEntity = new ArchivesDoc();
//					docEntity.setState("3");
//					archivesDocMapper.update(docEntity, updateWrapper);
//				}
//			}
//			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
//		} catch (Exception e) {
//			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", "");
//		}
//	}
}
